<template>
  <div class="ai-query-container">
    <el-card class="query-card">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Search /></el-icon>
            智能查询
          </span>
          <span class="subtitle">使用自然语言描述您的查询需求</span>
        </div>
      </template>

      <!-- 查询输入区域 -->
      <div class="query-input-section">
        <el-form :model="queryForm" label-width="80px">
          <el-form-item label="查询描述">
            <el-input
              v-model="queryForm.query"
              type="textarea"
              :rows="3"
              placeholder="例如：查询所有学生的姓名和年龄；统计每个系的学生人数；查找成绩大于90分的学生信息"
              :disabled="loading"
            />
          </el-form-item>
          
          <el-form-item>
            <el-checkbox v-model="queryForm.needExplanation" :disabled="loading">
              需要详细解释
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              @click="executeQuery" 
              :loading="loading"
              :disabled="!queryForm.query.trim()"
            >
              <el-icon><Search /></el-icon>
              执行查询
            </el-button>
            
            <el-button @click="clearQuery" :disabled="loading">
              <el-icon><RefreshLeft /></el-icon>
              清空
            </el-button>
            
            <el-button @click="showExamples" type="info" plain>
              <el-icon><QuestionFilled /></el-icon>
              查看示例
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 查询结果区域 -->
    <el-card v-if="queryResult" class="result-card">
      <template #header>
        <div class="result-header">
          <span class="result-title">
            <el-icon><DataBoard /></el-icon>
            查询结果
          </span>
          <div class="result-meta">
            <el-tag v-if="queryResult.success" type="success">查询成功</el-tag>
            <el-tag v-else type="danger">查询失败</el-tag>
            <span v-if="queryResult.success" class="meta-info">
              共 {{ queryResult.totalCount }} 条记录，耗时 {{ queryResult.executionTime }}ms
            </span>
          </div>
        </div>
      </template>

      <!-- 错误信息 -->
      <el-alert
        v-if="!queryResult.success"
        :title="queryResult.errorMessage"
        type="error"
        show-icon
        :closable="false"
      />

      <!-- 成功结果 -->
      <div v-else>
        <!-- 查询信息 -->
        <div class="query-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="查询意图">{{ queryResult.parsedIntent || '数据查询' }}</el-descriptions-item>
            <el-descriptions-item label="生成SQL">
              <el-button type="text" @click="showSql = !showSql">
                {{ showSql ? '隐藏' : '查看' }} SQL
              </el-button>
            </el-descriptions-item>
          </el-descriptions>
          
          <el-collapse-transition>
            <div v-show="showSql" class="sql-display">
              <el-input
                v-model="queryResult.generatedSql"
                type="textarea"
                :rows="3"
                readonly
                class="sql-textarea"
              />
            </div>
          </el-collapse-transition>
        </div>

        <!-- 数据表格 -->
        <div v-if="queryResult.data && queryResult.data.length > 0" class="data-table">
          <el-table
            :data="queryResult.data"
            border
            stripe
            :max-height="400"
            style="width: 100%"
          >
            <el-table-column
              v-for="column in queryResult.columns"
              :key="column.name"
              :prop="column.name"
              :label="column.label || column.name"
              :width="getColumnWidth(column.type)"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                <span>{{ formatCellValue(row[column.name], column.type) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空数据提示 -->
        <el-empty
          v-else
          description="未找到符合条件的数据"
          :image-size="100"
        />

        <!-- 查询解释 -->
        <div v-if="queryResult.explanation" class="explanation">
          <el-divider content-position="left">
            <el-icon><InfoFilled /></el-icon>
            查询解释
          </el-divider>
          <div class="explanation-content">
            {{ queryResult.explanation }}
          </div>
        </div>
      </div>
    </el-card>

    <!-- 示例对话框 -->
    <el-dialog v-model="examplesVisible" title="查询示例" width="600px">
      <div class="examples-content">
        <h4>基础查询示例：</h4>
        <ul>
          <li @click="useExample('查询所有学生的姓名和年龄')" class="example-item">
            查询所有学生的姓名和年龄
          </li>
          <li @click="useExample('查找计算机系的所有学生')" class="example-item">
            查找计算机系的所有学生
          </li>
          <li @click="useExample('查询成绩大于90分的学生信息')" class="example-item">
            查询成绩大于90分的学生信息
          </li>
        </ul>
        
        <h4>统计查询示例：</h4>
        <ul>
          <li @click="useExample('统计每个系的学生人数')" class="example-item">
            统计每个系的学生人数
          </li>
          <li @click="useExample('计算所有学生的平均成绩')" class="example-item">
            计算所有学生的平均成绩
          </li>
          <li @click="useExample('查询每门课程的选课人数')" class="example-item">
            查询每门课程的选课人数
          </li>
        </ul>
        
        <h4>复杂查询示例：</h4>
        <ul>
          <li @click="useExample('查询选修了数据库课程的学生姓名和成绩')" class="example-item">
            查询选修了数据库课程的学生姓名和成绩
          </li>
          <li @click="useExample('找出平均成绩最高的前5名学生')" class="example-item">
            找出平均成绩最高的前5名学生
          </li>
          <li @click="useExample('查询没有选课的学生信息')" class="example-item">
            查询没有选课的学生信息
          </li>
        </ul>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, RefreshLeft, QuestionFilled, DataBoard, InfoFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const showSql = ref(false)
const examplesVisible = ref(false)
const queryResult = ref(null)

const queryForm = reactive({
  query: '',
  needExplanation: true
})

// 执行查询
const executeQuery = async () => {
  if (!queryForm.query.trim()) {
    ElMessage.warning('请输入查询描述')
    return
  }

  loading.value = true
  queryResult.value = null

  try {
    const response = await request.post('/ai-query/query', {
      query: queryForm.query,
      needExplanation: queryForm.needExplanation
    })

    console.log('AI查询完整响应:', response)
    
    // 修正：response本身就包含code，不需要取response.data
    const responseData = response
    
    if (responseData && responseData.code === 200) {
      // 将后端返回的data字段赋值给queryResult
      queryResult.value = responseData.data
      console.log('查询结果数据:', queryResult.value)
      console.log('查询结果columns:', queryResult.value?.columns)
      console.log('查询结果data:', queryResult.value?.data)
      console.log('data长度:', queryResult.value?.data?.length)
      
      if (queryResult.value && queryResult.value.success) {
        ElMessage.success('查询执行成功')
      } else {
        console.error('查询失败，错误信息:', queryResult.value?.errorMessage)
        ElMessage.error(`查询执行失败: ${queryResult.value?.errorMessage || '未知错误'}`)
      }
    } else {
      console.error('API返回错误，响应码:', responseData?.code)
      ElMessage.error(responseData?.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('网络请求失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 清空查询
const clearQuery = () => {
  queryForm.query = ''
  queryForm.needExplanation = true
  queryResult.value = null
  showSql.value = false
}

// 显示示例
const showExamples = () => {
  examplesVisible.value = true
}

// 使用示例
const useExample = (example) => {
  queryForm.query = example
  examplesVisible.value = false
}

// 获取列宽度
const getColumnWidth = (type) => {
  if (type && type.toLowerCase().includes('text')) {
    return 200
  }
  return 120
}

// 格式化单元格值
const formatCellValue = (value, type) => {
  if (value === null || value === undefined) {
    return '-'
  }
  
  if (typeof value === 'number' && type && type.toLowerCase().includes('decimal')) {
    return value.toFixed(2)
  }
  
  return value
}
</script>

<style scoped>
.ai-query-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.query-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
}

.subtitle {
  font-size: 14px;
  color: #666;
}

.query-input-section {
  padding: 10px 0;
}

.result-card {
  margin-top: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.result-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.meta-info {
  font-size: 12px;
  color: #666;
}

.query-info {
  margin-bottom: 20px;
}

.sql-display {
  margin-top: 10px;
}

.sql-textarea {
  font-family: 'Courier New', monospace;
}

.data-table {
  margin: 20px 0;
}

.explanation {
  margin-top: 20px;
}

.explanation-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  white-space: pre-line;
  font-size: 14px;
  line-height: 1.6;
}

.examples-content h4 {
  color: #409eff;
  margin: 15px 0 10px 0;
}

.examples-content ul {
  list-style: none;
  padding: 0;
}

.example-item {
  padding: 8px 12px;
  margin: 5px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.example-item:hover {
  background-color: #e6f7ff;
  color: #409eff;
}

/* 表格样式 - 统一对齐方式 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: left !important;
}

:deep(.el-table td) {
  text-align: left !important;
}

:deep(.el-table .cell) {
  text-align: left !important;
}

@media (max-width: 768px) {
  .ai-query-container {
    padding: 10px;
  }
  
  .result-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>